package com.gxa.check.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.check.dao.DeptDao;
import com.gxa.check.dao.ExaminePeopleDao;
import com.gxa.check.service.OrderService;
import com.gxa.check.service.UserService;

import dto.ResultDTO;
import entity.*;
import com.gxa.check.dao.ExamineDao;
import com.gxa.check.service.ExamineService;
import exception.SystemException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.Response;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/**
 * 审核表(Examine)表服务实现类
 *
 * @author makejava
 * @since 2021-05-11 15:23:47
 */
@Service("examineService")
@SuppressWarnings("all")
@Transactional(rollbackFor = Throwable.class)
public class ExamineServiceImpl implements ExamineService {
    @Resource
    private ExamineDao examineDao;
    @Resource
    private OrderService orderService;
    @Resource
    private UserService userService;
    @Resource
    private ExaminePeopleDao examinePeopleDao;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private DeptDao deptDao;

    @Override
    public ResultDTO addMac(Integer macOrderId) {
        if (macOrderId == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        if (examineDao.findByMacOrderId(macOrderId) != null) {
            throw new SystemException(1001, "该订单已经审核");
        }
        //查询订单
        ResultDTO macOrderDTO = orderService.findByMacOrderId(macOrderId);
        ObjectMapper objectMapper = new ObjectMapper();
        MacOrder macOrder = objectMapper.convertValue(macOrderDTO.getData(), MacOrder.class);
        System.out.println(macOrder);
        if (macOrder == null) {
            throw new SystemException(1001, "没有该订单");
        }
        //获取申请人的ID
        Integer applyId = macOrder.getApplyId();
        //根据id查询该用户
        ResultDTO memberDTO = userService.findByMemberId(applyId);
        Member dbMember = objectMapper.convertValue(memberDTO.getData(), Member.class);
        Integer roleId = dbMember.getRoleId();
        //判断申请人角色
        if (roleId == 4) {
            //角色为普通员工
            //判断部门
            Integer deptId = dbMember.getDeptId();
            //判断该角色的上级
            ResultDTO newMemberDTO = userService.findByDeptIdAndRoleId(deptId, roleId);
            Member newMember = objectMapper.convertValue(newMemberDTO.getData(), Member.class);
            //给该上级添加到审核表
            Examine examine = new Examine();
            examine.setExamineOrderId(macOrderId);
            examine.setExamineFirstMemberId(newMember.getMemberId());

            examineDao.insert(examine);
            return Response.success(200, "预定成功，请等待审核", 1);
        }else if (roleId == 2) {
            //当前角色为部门经理
            //获取角色为总经理的用户
            ResultDTO newMemberDTO = userService.findBoss();
            Member newMember = objectMapper.convertValue(newMemberDTO.getData(), Member.class);
            //给该上级添加到审核表
            Examine examine = new Examine();
            examine.setExamineOrderId(macOrderId);
            examine.setExamineFirstIsPoss(1);
            examine.setExamineFirstDoTime(new Timestamp(System.currentTimeMillis()));
            examine.setExamineFirstMemberId(dbMember.getMemberId());
            examine.setExamineSecondMemberId(newMember.getMemberId());

            examineDao.insert(examine);
            return Response.success(200, "预定成功，请等待审核", 1);
        }else if (roleId == 1 || roleId == 3) {
            //当前角色为总经理和管理员
            //给该上级添加到审核表
            Examine examine = new Examine();
            examine.setExamineOrderId(macOrderId);
            examine.setExamineFirstIsPoss(1);
            examine.setExamineFirstDoTime(new Timestamp(System.currentTimeMillis()));
            examine.setExamineFirstMemberId(dbMember.getMemberId());
            examine.setExamineSecondIsPoss(1);
            examine.setExamineSecondDoTime(new Timestamp(System.currentTimeMillis()));
            examine.setExamineSecondMemberId(dbMember.getMemberId());
            examineDao.insert(examine);
            //修改订单状态为代出票
            orderService.manageMacPass(macOrderId);
            //验证是否修改成功
            ResultDTO newMacOrderDTO = orderService.findByMacOrderId(macOrderId);
            MacOrder newMacOrder = objectMapper.convertValue(newMacOrderDTO.getData(), MacOrder.class);
            if (newMacOrder.getMacOrderStatus() != 4) {
                throw new SystemException(1001, "订单修改失败，请重新修改");
            }
            //添加到待出票的消息队列
            Message message = new GenericMessage(macOrder);
            rocketMQTemplate.syncSend("macOrder-topic",message,6000,5);
            return Response.success(200, "审核成功，等待出票", "1");
        }
        return Response.error(1002,"预定失败");
    }

    @Override
    public ResultDTO possMacOrder(Integer macOrderId, Integer memberId) {
        if (macOrderId == null || memberId == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        //根据订单ID查询机械单的审核表
        Examine dbExamine = examineDao.findByMacOrderId(macOrderId);
        if (dbExamine == null) {
            throw new SystemException(1002, "订单不存在");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //通过用户ID查询用户
        ResultDTO memberDto = userService.findAllById(memberId);
        Member newMember = objectMapper.convertValue(memberDto.getData(), Member.class);
        Integer roleId = newMember.getRoleId();
        //判断角色
        if (roleId == 4) {
            //普通员工
            throw new SystemException(1002, "你没有权限");
        } else if (roleId == 3) {
            //管理员
            throw new SystemException(1002, "管理员不能审核机械单");
        } else if (roleId == 2) {
            //部门经理
            //通过一级审核
            if (dbExamine.getExamineFirstIsPoss() == null) {
                //通过一级审核
                dbExamine.setExamineFirstIsPoss(1);
                //审核人
                dbExamine.setExamineFirstMemberId(memberId);
                //通过时间
                dbExamine.setExamineFirstDoTime(new Timestamp(System.currentTimeMillis()));
                //修改审核表
                examineDao.update(dbExamine);
                //改成审核中
                orderService.manageMacIn(macOrderId);
                return Response.error(200, "一级审核通过，请等待二级审核");
            }
            //二级审核
            if (dbExamine.getExamineSecondIsPoss() == null && dbExamine.getExamineFirstIsPoss() != null ) {
                throw new SystemException(1002, "你没有权限审批二级审核");
            }
        }else if (roleId == 1) {
            //总经理
            if (dbExamine.getExamineFirstIsPoss() == null) {
                //通过一级审核
                dbExamine.setExamineFirstIsPoss(1);
                //通过时间
                dbExamine.setExamineFirstDoTime(new Timestamp(System.currentTimeMillis()));
                //审核人
                dbExamine.setExamineFirstMemberId(memberId);
                //修改审核表
                examineDao.update(dbExamine);
                //改成代出票
                orderService.manageMacPass(macOrderId);
                //添加至队列
                MacOrder macOrder = new MacOrder();
                macOrder.setMacOrderId(macOrderId);
                Message message = new GenericMessage(macOrder);
                rocketMQTemplate.syncSend("macOrder-topic",message,6000,5);
                return Response.error(200, "审核通过，等待出票");
            }
            if (dbExamine.getExamineSecondIsPoss() == null && dbExamine.getExamineFirstIsPoss() != null) {
                //二级审核
                //增加二级审核人
                dbExamine.setExamineSecondMemberId(memberId);
                //通过二级审核
                dbExamine.setExamineSecondIsPoss(1);
                //通过时间
                dbExamine.setExamineSecondDoTime(new Timestamp(System.currentTimeMillis()));
                //修改审核表
                examineDao.update(dbExamine);
                //修改订单状态
                orderService.manageMacPass(macOrderId);
                //验证是否修改成功
                ResultDTO newMacOrderDTO = orderService.findByMacOrderId(macOrderId);
                MacOrder newMacOrder = objectMapper.convertValue(newMacOrderDTO.getData(), MacOrder.class);
                if (newMacOrder.getMacOrderStatus() != 4) {
                    throw new SystemException(1001, "订单修改失败，请重新修改");
                }
                //添加至队列
                MacOrder macOrder = new MacOrder();
                macOrder.setMacOrderId(macOrderId);
                Message message = new GenericMessage(macOrder);
                rocketMQTemplate.syncSend("macOrder-topic",message,6000,5);
                return Response.success("二级审核通过，等待出票");
            }
        }
        if (dbExamine.getExamineFirstIsPoss() != null && dbExamine.getExamineSecondIsPoss() != null) {
            return Response.success("该订单已经审核");
        }
        return Response.error(1002, "审核失败");
    }

    @Override
    public ResultDTO refuseMacOrder(Integer macOrderId, String refuseMsg, Integer memberId) {
        if (macOrderId == null || memberId == null || refuseMsg == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        //根据订单ID查询机械单的审核表
        Examine dbExamine = examineDao.findByMacOrderId(macOrderId);
        if (dbExamine == null) {
            throw new SystemException(1002, "订单不存在");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //通过用户ID查询用户
        ResultDTO memberDto = userService.findAllById(memberId);
        Member newMember = objectMapper.convertValue(memberDto.getData(), Member.class);
        Integer roleId = newMember.getRoleId();
        if (roleId == 4) {
            //普通员工
            throw new SystemException(1002, "你没有权限");
        }else if (roleId == 3) {
            throw new SystemException(1002, "管理员不能审核机械单");
        }else if (roleId == 2) {
            //部门经理
            if (dbExamine.getExamineFirstIsPoss() == null) {
                //拒接订单
                dbExamine.setExamineFirstIsPoss(0);
                //添加拒绝理由
                dbExamine.setExamineFirstRefuseDesc(refuseMsg);
                //添加操作时间
                dbExamine.setExamineFirstDoTime(new Timestamp(System.currentTimeMillis()));
                //审核人
                dbExamine.setExamineFirstMemberId(memberId);
                //修改
                examineDao.update(dbExamine);
                //修改订单状态未拒绝
                orderService.manageMacCancel(macOrderId);
                return Response.success("已取消该申请");
            }
            if (dbExamine.getExamineSecondIsPoss() == null && dbExamine.getExamineFirstIsPoss() != null) {
                throw new SystemException(1002, "你没有权限");
            }
        }else if (roleId == 1) {
            //总经理
            if (dbExamine.getExamineFirstIsPoss() == null) {
                //拒接订单
                dbExamine.setExamineFirstIsPoss(0);
                //添加拒绝理由
                dbExamine.setExamineFirstRefuseDesc(refuseMsg);
                //添加操作时间
                dbExamine.setExamineFirstDoTime(new Timestamp(System.currentTimeMillis()));
                //审核人
                dbExamine.setExamineFirstMemberId(memberId);
                //修改
                examineDao.update(dbExamine);
                //修改订单状态未拒绝
                orderService.manageMacCancel(macOrderId);
                return Response.success("已取消该申请");
            }
            if (dbExamine.getExamineSecondIsPoss() == null && dbExamine.getExamineFirstIsPoss() != null) {
                //拒接订单
                dbExamine.setExamineSecondIsPoss(0);
                //添加拒绝理由
                dbExamine.setExamineSecondRefuseDesc(refuseMsg);
                //添加操作时间
                dbExamine.setExamineSecondDoTime(new Timestamp(System.currentTimeMillis()));
                //增加二级审核人
                dbExamine.setExamineSecondMemberId(memberId);
                //修改
                examineDao.update(dbExamine);
                //修改订单状态
                orderService.manageMacCancel(macOrderId);
                return Response.success("该订单已拒绝");
            }
        }
        if (dbExamine.getExamineFirstIsPoss() != null && dbExamine.getExamineSecondIsPoss() != null) {
            return Response.success("不用重复审核");
        }
        return Response.error(1003, "操作失败");
    }

    @Override
    public ResultDTO possArtOrder(Integer artOrderId, Integer memberId) {
        ObjectMapper objectMapper = new ObjectMapper();
        if (artOrderId == null || memberId ==null) {
            throw new SystemException(1001, "获取数据失败");
        }
        //判断审核人的角色
        ResultDTO memberDto = userService.findByMemberId(memberId);
        Member memberDate = objectMapper.convertValue(memberDto.getData(), Member.class);
        if (memberDate.getRoleId() != 3) {
            return Response.error(1002, "你没有该权限");
        }
        //根据订单ID查询
        if (examinePeopleDao.findByOrderId(artOrderId) != null) {
            throw new SystemException(1001, "该订单已经审核，无法再次审核");
        }
        ExaminePeople examinePeople = new ExaminePeople();
        //人工单ID
        examinePeople.setExaOrderId(artOrderId);
        //审核人ID
        examinePeople.setExaMemberId(memberId);
        //通过
        examinePeople.setExaIsPoss(1);
        //操作时间
        examinePeople.setExaDoTime(new Timestamp(System.currentTimeMillis()));
        //增加
        if (examinePeopleDao.insert(examinePeople) <= 0) {
            throw new SystemException(1003, "审核失败");
        }
        //修改人工单的状态
        orderService.manageArtPass(artOrderId);
        //验证是否修改成功
        ResultDTO newArtOrderDTO = orderService.findByArtOrderId(artOrderId);
        ArtOrder newArtOrder = objectMapper.convertValue(newArtOrderDTO.getData(), ArtOrder.class);
        if (newArtOrder.getArtOrderStatus() != 4) {
            throw new SystemException(1001, "订单修改失败，请重新修改");
        }
        //添加至队列
        ArtOrder artOrder = new ArtOrder();
        artOrder.setArtOrderId(artOrderId);
        Message message = new GenericMessage(artOrder);
        rocketMQTemplate.syncSend("artOrder-topic",message,6000,5);
        return Response.success("该审核单已通过");
    }

    @Override
    public ResultDTO refuseArtOrder(Integer artOrderId, Integer memberId, String refuseMsg) {
        if (artOrderId == null || memberId ==null || refuseMsg == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //判断审核人的角色
        ResultDTO memberDto = userService.findByMemberId(memberId);
        Member memberDate = objectMapper.convertValue(memberDto.getData(), Member.class);
        if (memberDate.getRoleId() != 3) {
            return Response.error(1002, "你没有该权限");
        }
        //根据订单ID查询
        if (examinePeopleDao.findByOrderId(artOrderId) != null) {
            throw new SystemException(1001, "该订单已经审核，无法再次审核");
        }
        ExaminePeople examinePeople = new ExaminePeople();
        //人工单ID
        examinePeople.setExaOrderId(artOrderId);
        //审核人ID
        examinePeople.setExaMemberId(memberId);
        //拒绝
        examinePeople.setExaIsPoss(0);
        //操作时间
        examinePeople.setExaDoTime(new Timestamp(System.currentTimeMillis()));
        //设置拒绝理由
        examinePeople.setExaRefuseDesc(refuseMsg);
        //增加
        if (examinePeopleDao.insert(examinePeople) <= 0) {
            throw new SystemException(1003, "操作失败");
        }
        //修改人工单的状态
        orderService.manageArtCancel(artOrderId);
        return Response.success("该审核单已拒绝");
    }

    @Override
    public ResultDTO exaMacOrderMember(Integer macOrderId) {
        ObjectMapper objectMapper = new ObjectMapper();
        if (macOrderId == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        //根据订单ID查询
        Examine examine = examineDao.findByMacOrderId(macOrderId);
        if (examine == null) {
            throw new SystemException(1001, "该订单没有审核");
        }
        if (examine.getExamineFirstIsPoss() == null) {
            return Response.success(200, "success", "占未审核");
        }
        if (examine.getExamineFirstIsPoss() != null && examine.getExamineSecondIsPoss() == null) {
            //获取名字
            ResultDTO memberDTO = userService.findByMemberId(examine.getExamineFirstMemberId());
            Member member = objectMapper.convertValue(memberDTO.getData(), Member.class);
            String memberName = member.getMemberName();
            return Response.success(200, "success", "一级审核人："+memberName+",二级未审核");
        }
        if (examine.getExamineFirstIsPoss() != null && examine.getExamineSecondIsPoss() != null) {
            //获取名字
            ResultDTO firstMemberDTO = userService.findByMemberId(examine.getExamineFirstMemberId());
            ResultDTO secondMemberDTO = userService.findByMemberId(examine.getExamineSecondMemberId());
            Member firstMember = objectMapper.convertValue(firstMemberDTO.getData(), Member.class);
            Member secondMember = objectMapper.convertValue(secondMemberDTO.getData(), Member.class);
            String firstMemberName = firstMember.getMemberName();
            String secondMemberName = secondMember.getMemberName();
            return Response.success(200, "success", "一级审核人："+firstMemberName+",二级审核人："+secondMemberName);
        }
        return Response.error(1001, "查询订单失败");
    }

    @Override
    public ResultDTO exaArtOrderMember(Integer artOrderId) {
        ObjectMapper objectMapper = new ObjectMapper();
        if (artOrderId == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        ExaminePeople examinePeople = examinePeopleDao.findByOrderId(artOrderId);
        if (examinePeople == null) {
            throw new SystemException(1001, "该订单没有审核");
        }
        //获取审批人
        ResultDTO memberDTO = userService.findByMemberId(examinePeople.getExaMemberId());
        Member member = objectMapper.convertValue(memberDTO.getData(), Member.class);
        if (member == null) {
            throw new SystemException(1002, "没有该用户");
        }
        String memberName = member.getMemberName();
        return Response.success(200, "success", "审核人："+memberName);
    }

    @Override
    public ResultDTO checkOrder(Integer orderId, Integer type) {
        if (orderId == null || type == null) {
            throw new SystemException(1001, "获取数据失败");
        }
        if (type == 0) {
            //人工单
            ExaminePeople examinePeople = examinePeopleDao.findByOrderId(orderId);
            if (examinePeople == null) {
                throw new SystemException(1002, "没有该订单");
            }
            return Response.success(examinePeople);
        }else if (type == 1) {
            //机械单
            Examine examine = examineDao.findByMacOrderId(orderId);
            if (examine == null) {
                throw new SystemException(1003, "没有该订单");
            }
            return Response.success(examine);
        }
        return Response.error(1004, "查询失败");
    }

    @Override
    public ResultDTO findAllDept() {
        List<Dept> depts = deptDao.findAll();
        return Response.success(depts);
    }
}
